package org.tio.examples.httpImpl.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class CompletionHandlerImpl implements CompletionHandler<AsynchronousSocketChannel, Object>{
    
	private AsynchronousSocketChannel async = null;
    
    private ReadCompletionHandler readCompletionHandler = new ReadCompletionHandler(async);

	@Override
    public void completed(AsynchronousSocketChannel asynchronousSocketChannel, Object attachment) {
        this.async = asynchronousSocketChannel;
        try {
            InetSocketAddress inetSocketAddress = (InetSocketAddress) asynchronousSocketChannel.getRemoteAddress();
            String clientIp = inetSocketAddress.getHostString();
            asynchronousSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
            asynchronousSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 32 * 1024);
            asynchronousSocketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 32 * 1024);
            asynchronousSocketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
            ByteBuffer readByteBuffer = ByteBuffer.allocate(2048);
            asynchronousSocketChannel.read(readByteBuffer, readByteBuffer, readCompletionHandler);
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpImpl h = (HttpImpl) attachment;
            AsynchronousServerSocketChannel serverSocketChannel = h.getServerSocketChannel();
            serverSocketChannel.accept(attachment, this);
        }
    }

    @Override
    public void failed(Throwable exc, Object attachment) {
        
        
    }

  

}
